package com.bishe.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.bishe.common.utils.JwtUtils;
import com.bishe.common.utils.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换为Http协议
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求url
        String url = request.getRequestURI().toString();
        log.info("本次请求路径"+url);
        //2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if(url.contains("/login")||url.contains("/registered")||url.contains("/mail")){
            filterChain.doFilter(request, response);//放行请求
            return;//结束当前方法的执行
        }
        //2.获取token
        String token = request.getHeader("authorization");
        log.info("获取的token"+token);
        if(!StringUtils.hasLength(token)){
            R<String> r=new R<>();
            r.setMsg("未登录，请先登录！");
            r.setCode(401);
            String json = JSONObject.toJSONString(r);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);

            return;
        }
        //5.解析token，如果解析失败，返回错误结果（未登录）
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("令牌解析失败!");

            R<String> r=new R<>();
            r.setMsg("未登录，请先登录！");
            r.setCode(401);
            //把Result对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
            String json = JSONObject.toJSONString(r);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);

            return;

        }
        filterChain.doFilter(request, response);
    }
}
